<template>
  <div class="search">
    <input
      type="text"
      placeholder="请输入城市名字"
      spellcheck="false"
      v-model="cityName"
      @keydown="keyCode"
    />
    <button @click="search"><img src="../assets/images/search.png" /></button>
  
  </div>
</template>

<script>
import axios from "axios";
export default {
  name: "serach",
  data() {
    return {
      cityName: "",
    };
  },
  methods: {
    // 监听键盘事件
    keyCode(e) {
      if (e.keyCode === 13) {
        this.search();
      }
    },
    search() {
             //    请求接口  根据城市名字获取经度和纬度
      const apiKey = "acd12aeac70e905b26d3a2158e5fb416";
      let apiUrlGetLocation = `http://api.openweathermap.org/geo/1.0/direct?q=${this.cityName}&appid=${apiKey}`;
      if (!this.cityName.trim()) {
        alert("请输入城市名字");
        return;
      }
      axios.get(apiUrlGetLocation).then((response) => {
        if (!response.data.length) {
          // $emit 参数1：事件名称，参数N：传递的数据....
          this.$bus.$emit("displayisNotFound", true);
        } else {
          let lat = response.data[0].lat;
          let lon = response.data[0].lon;
          let apiUrlGetWeather = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`;
          axios.get(apiUrlGetWeather).then((response) => {
            // 将返回的数据封住为一个对象传给weather组件
            let icon = `https://openweathermap.org/img/wn/${response.data.weather[0].icon}@2x.png`;
            let weatherObj = {
              // icon路径
              icon: icon,
              // 温度
              temp: response.data.main.temp,
              // 湿度
              humidity: response.data.main.humidity,
              // 风速
              windSpeed: response.data.wind.speed,
              // 城市名
              cityName: this.cityName,
              // 是否展示
              isShow: true,
              // 是否提示城市名合法
              isNotFound: false,
            };
            // 将数据传给weather组件
            this.$bus.$emit("displayWeather", weatherObj);
          });
        }
      });
    }
  },
};
</script>

<style lang="css" scoped>
/*搜索框样式*/
.search {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.search input {
  border: 0;
  outline: 0;
  background: #ebfffc;
  color: #555;
  padding: 10px 25px;
  height: 60px;
  border-radius: 30px;
  flex: 1;
  margin-right: 16px;
  font-size: 18px;
}

.search button {
  border: 0;
  outline: 0;
  background: #ebfffc;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  cursor: pointer;
}

.search button img {
  width: 16px;
}
</style>